package cn.edu.ldu.views.main;

import cn.edu.ldu.controller.FriendController;
import cn.edu.ldu.controller.GroupController;
import cn.edu.ldu.controller.UserController;
import cn.edu.ldu.entity.*;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.*;
import cn.edu.ldu.views.login.LoginUI;
import cn.edu.ldu.views.main.util.ListModel;
import cn.edu.ldu.views.operator.GroupMegUI;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author DYZ
 */
public class MainUI extends javax.swing.JFrame {

    private JButton btnCheckList;
    private JButton btnMessage;
    private JButton btnUser;
    private JButton btnFriendsInfo;
    private JButton btnRelogin;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JScrollPane jScrollPane1;
    private JList<String> listFriends;
    private JPanel listPanel;
    private JPanel middlePanel;
    private JPanel topPanel;
    private ListModel friends;
    //获取朋友列表的朋友
    private FriendsEntity Fstr;
    private GroupChatEntity Gctr;
    HashMap<String, Object> content;
    private ChatUI chatUI;
    private GroupChatUI groupChatUI;
    /**
     * Creates new form MainUIController
     */
    public MainUI(HashMap<String, Object> content) {
        try {
            DatagramSocket datagramSocket = Ports.getCommon();
            new ReceiveMessage(datagramSocket, this).start();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        this.content = content;
        initComponents();
        loadAvatar(UserController.getUserAccountEntity().getUserAvatar());
    }

    //好友上线
    public void updateFrinedList(String username){
        friends.addElement(username);
        listFriends.setModel(friends);
        jScrollPane1.setViewportView(listFriends);
        jScrollPane1.updateUI();
    }

    //好友下线
    public void deleteFriendList(String username){
        friends.removeElement(username);
        listFriends.setModel(friends);
        jScrollPane1.setViewportView(listFriends);
        jScrollPane1.updateUI();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        topPanel = new javax.swing.JPanel();
        btnUser = new javax.swing.JButton();
        btnMessage = new javax.swing.JButton();
        btnCheckList = new javax.swing.JButton();
        btnFriendsInfo = new javax.swing.JButton();
        btnRelogin = new javax.swing.JButton();
        listPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listFriends = new javax.swing.JList<>();
        middlePanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        friends = new ListModel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/user.png"))); // NOI18N
        btnUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnUserMouseClicked(evt);
            }
        });


        btnMessage.setText("打开消息面板");
        btnMessage.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnMessageMouseClicked(evt);
            }
        });

        btnCheckList.setText("查看好友列表");
        btnCheckList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCheckListMouseClicked(evt);
            }
        });

        btnFriendsInfo.setText("查看好友信息");
        btnFriendsInfo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnFriendsInfoMouseClicked(evt);
            }
        });

        btnRelogin.setText("注销当前账户");
        btnRelogin.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnReloginMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
        topPanel.setLayout(topPanelLayout);
        topPanelLayout.setHorizontalGroup(
                topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(topPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(btnUser, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                                .addComponent(btnMessage)
                                .addGap(36, 36, 36)
                                .addComponent(btnCheckList)
                                .addGap(57, 57, 57)
                                .addComponent(btnFriendsInfo)
                                .addGap(35, 35, 35)
                                .addComponent(btnRelogin)
                                .addGap(31, 31, 31))
        );
        topPanelLayout.setVerticalGroup(
                topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(topPanelLayout.createSequentialGroup()
                                .addComponent(btnUser, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addContainerGap())
                        .addGroup(topPanelLayout.createSequentialGroup()
                                .addGap(22, 22, 22)
                                .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnMessage)
                                        .addComponent(btnCheckList)
                                        .addComponent(btnFriendsInfo)
                                        .addComponent(btnRelogin))
                                .addContainerGap(26, Short.MAX_VALUE))
        );

        getContentPane().add(topPanel, java.awt.BorderLayout.PAGE_START);

        listPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("当前在线好友"));

        /**
         * 获取好友以及群聊列表
         */
        List<FriendsEntity> friendsList =  JSONObject.parseArray(content.get(Consts.K_ONLINE_FRIEND).toString(), FriendsEntity.class);
        L.OK(friendsList, MainUI.class);
        /**
         * 添加在线好友信息
         */
        for(int i=0;i<friendsList.size();i++){
            friends.addElement(friendsList.get(i).getUserAccountEntity().getNickName(), friendsList.get(i).getFriendId(),0);
        }
        /**
         * 添加群聊信息
         */
        List<GroupChatEntity> groupsList = JSONObject.parseArray(content.get(Consts.K_GROUP_CHAT).toString(),GroupChatEntity.class);;
        for(int i=0;i<groupsList.size();i++){
            friends.addElement(groupsList.get(i).getGroupName(),groupsList.get(i).getId(),1);
        }
        listFriends.setModel(friends);

        jScrollPane1.setViewportView(listFriends);

        javax.swing.GroupLayout listPanelLayout = new javax.swing.GroupLayout(listPanel);
        listPanel.setLayout(listPanelLayout);
        listPanelLayout.setHorizontalGroup(
                listPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
        );
        listPanelLayout.setVerticalGroup(
                listPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
        );

        getContentPane().add(listPanel, java.awt.BorderLayout.LINE_START);

        jLabel1.setText("欢迎来到聊天界面");

        jLabel2.setText("选择好友，然后点击上方进行操作");

        javax.swing.GroupLayout middlePanelLayout = new javax.swing.GroupLayout(middlePanel);
        middlePanel.setLayout(middlePanelLayout);
        middlePanelLayout.setHorizontalGroup(
                middlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(middlePanelLayout.createSequentialGroup()
                                .addGroup(middlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(middlePanelLayout.createSequentialGroup()
                                                .addGap(133, 133, 133)
                                                .addComponent(jLabel2))
                                        .addGroup(middlePanelLayout.createSequentialGroup()
                                                .addGap(180, 180, 180)
                                                .addComponent(jLabel1)))
                                .addContainerGap(316, Short.MAX_VALUE))
        );
        middlePanelLayout.setVerticalGroup(
                middlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(middlePanelLayout.createSequentialGroup()
                                .addGap(90, 90, 90)
                                .addComponent(jLabel1)
                                .addGap(30, 30, 30)
                                .addComponent(jLabel2)
                                .addContainerGap(274, Short.MAX_VALUE))
        );

        getContentPane().add(middlePanel, BorderLayout.CENTER);

        pack();
    }// </editor-fold>

    /**
     * 用户信息界面
     */
    private void btnUserMouseClicked(java.awt.event.MouseEvent evt){
        UserInfoUI userInfo = new UserInfoUI(middlePanel.getWidth(),middlePanel.getHeight());
        middlePanel.removeAll();
        middlePanel.add(userInfo);
        middlePanel.updateUI();
        middlePanel.repaint();
    }

    /**
     * 发信息面板
     * 需要判定是好友还是群聊
     */
    private void btnMessageMouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
        //没选中朋友
        if(listFriends.getSelectedValue() == null ){
            JOptionPane.showMessageDialog(null, "请选择一个好友", "标题【错误】", JOptionPane.ERROR_MESSAGE);
        }else{
            //需要判定是好友还是群聊
            if (friends.getType(listFriends.getSelectedIndex()) == 0){
                //判定是好友
                Fstr = new FriendsEntity();
                Fstr = FriendController.getFriendsEntity(friends.getUserIds( listFriends.getSelectedIndex()));
                chatUI = new ChatUI(middlePanel.getWidth(),middlePanel.getHeight(),Fstr);
                middlePanel.removeAll();
                middlePanel.add(chatUI);
                middlePanel.updateUI();
                middlePanel.repaint();
            }else {
                //判定是群聊
                Gctr = new GroupChatEntity();
                Gctr = GroupController.getGroupChatEntity(friends.getUserIds(listFriends.getSelectedIndex()));
                L.OK(Gctr, MainUI.class);
                //发送需要得到群聊成员的信息
                InetAddress remoteAddr = null;
                try {
                    remoteAddr = InetAddress.getByName(Consts.ipv4);
                    //创建UDP套件字
                    DatagramSocket clientSocket = null;
                    clientSocket = new DatagramSocket();
                    clientSocket.setSoTimeout(5000);

                    //构造得到群聊信息
                    Protocol protocol = new Protocol();
                    protocol.setKey("GetChatMember");
                    protocol.setToken(UserController.getToken());

                    //转字符
                    protocol.setData(JSON.toJSONString(Gctr.getId()));

                    byte[] data = Translate.ObjectToByte(protocol);

                    //定义得到群聊成员报文
                    DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);

                    clientSocket.send(packet);
                    L.OK(packet,MainUI.class);

                    byte[] receiveDta = new byte[8096];
                    packet = new DatagramPacket(receiveDta,receiveDta.length,remoteAddr,Consts.port);
                    clientSocket.receive(packet);

                    L.OK(packet,MainUI.class);

                    L.OK(GroupController.getGroupMenberlist(), MainUI.class);
                    groupChatUI = new GroupChatUI(middlePanel.getWidth(),middlePanel.getHeight(),Gctr);
                    middlePanel.removeAll();
                    middlePanel.add(groupChatUI);
                    middlePanel.updateUI();
                    middlePanel.repaint();

                    Protocol pro = (Protocol) Translate.ByteToObject(packet.getData());
                    pro.key();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 查看好友列表
     * @param evt
     */
    private void btnCheckListMouseClicked(java.awt.event.MouseEvent evt){
        FriendsUI friends = new FriendsUI(middlePanel.getWidth(),middlePanel.getHeight());
        middlePanel.removeAll();
        middlePanel.add(friends);
        middlePanel.updateUI();
        middlePanel.repaint();
    }

    /**
     * 查看好友信息
     * @param evt
     */
    private void btnFriendsInfoMouseClicked(java.awt.event.MouseEvent evt){
        //没选中朋友
        if(listFriends.getSelectedValue() == null){
            JOptionPane.showMessageDialog(null, "请选择一个好友", "标题【错误】", JOptionPane.ERROR_MESSAGE);
        }else{
            //需要判定是好友还是群聊
            if (friends.getType(listFriends.getSelectedIndex())==0){
                //判定是好友
                Fstr = new FriendsEntity();
                Fstr = FriendController.getFriendsEntity(friends.getUserIds(listFriends.getSelectedIndex()));
                CheckFriendsUI checkFriends = new CheckFriendsUI(middlePanel.getWidth(),middlePanel.getHeight(),Fstr);
                middlePanel.removeAll();
                middlePanel.add(checkFriends);
                middlePanel.updateUI();
                middlePanel.repaint();
            }else{
                //判定是群聊
                Gctr = new GroupChatEntity();
                Gctr = GroupController.getGroupChatEntity(friends.getUserIds(listFriends.getSelectedIndex()));
                new GroupMegUI(Gctr).setVisible(true);
            }

        }
    }

    /**
     * 注销当前用户
     * @param evt
     */
    private void btnReloginMouseClicked(java.awt.event.MouseEvent evt){
        //询问是否确定注销账户
        int res = JOptionPane.showConfirmDialog(null, "是否注销账户", "是否继续", JOptionPane.YES_NO_OPTION);
        if (res == JOptionPane.YES_OPTION) {
            // 点击“是”后执行这个代码块
            InetAddress remoteAddr = null;
            try {
                remoteAddr = InetAddress.getByName(Consts.ipv4);
                //创建UDP套件字
                DatagramSocket clientSocket = null;
                clientSocket = new DatagramSocket();
                clientSocket.setSoTimeout(5000);

                //构造用户退出信息
                Protocol protocol = new Protocol();
                protocol.setKey("Logout");

                protocol.setData(JSON.toJSONString(FriendController.getOnlineFriendsEntity()));


                byte[] data = Translate.ObjectToByte(protocol);

                //定义退出报文
                DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);

                //发送报文
                clientSocket.send(packet);
                L.OK(packet,MainUI.class);

             } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //界面消失，登录界面显示
            this.dispose();
            new LoginUI().setVisible(true);
        } else {
            return;
        }
    }

    /**
     * 接受信息
     * @param Msg
     */
    public void receiveMsg(ChatHistoryEntity Msg){
        chatUI.receiveMsg(Msg);
    }

    public void receiveGroupMsg(ChatHistoryEntity Msg){
        groupChatUI.receiveGroupMsg(Msg);
    }

    /**
     * 得到发信息的昵称
     * @return
     */
    public String getTalkerName(){
        return chatUI.getTalkerName();
    }

    public void loadAvatar(String avatar){
        try {
//            URL url = new URL("http://127.0.0.1:8080/ticktick/image/girl1.png");
            URL url = new URL("http://" + Consts.ipv4 + ":8080/ticktick/image/" + avatar);
            BufferedImage image = ImageIO.read(url);
            ImageIcon imageIcon;
            float scale;
            if(image.getHeight() < image.getWidth()){
                scale = (float)image.getWidth() / btnUser.getWidth();
            }else
                scale = (float)image.getHeight() / btnUser.getHeight();
            scale += 0.2;
            imageIcon = new ImageIcon(image.getScaledInstance((int) (image.getWidth() / scale), (int) (image.getHeight() / scale), Image.SCALE_SMOOTH));
            btnUser.setIcon(imageIcon);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 添加群聊信息
     */
    public void setChatMember(List<ChatMemberEntity> members){
        groupChatUI.setChatMember(members);
    }

    /**
     * 关闭窗口
     */

}